package cn.ibizlab.core.oauth2.config;

import cn.ibizlab.util.security.AuthenticationUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * OAuth2认证模式下将请求头中的预置参数填充至登录用户
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "ibiz.auth.security", havingValue = "oauth2",matchIfMissing = true)
public class OAuth2AuthenticationFilter extends OncePerRequestFilter {

    @Value("${ibiz.auth.excludesPattern:}")
    private String[] excludesPattens;
    private PathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 将请求头中的预置参数填充至登录用户
     * @param request
     * @param response
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (isExclusion(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
        Authentication authentication = SecurityContextHolder.getContext() != null ? SecurityContextHolder.getContext().getAuthentication() : null;
        if(authentication instanceof OAuth2Authentication && authentication.getPrincipal() != null && authentication.getPrincipal() instanceof AuthenticationUser)
        {
            ((AuthenticationUser) authentication.getPrincipal()).readHeader(false);
        }
        chain.doFilter(request, response);
    }

    /**
     * 排除免认证请求
     * @param requestURI
     * @return
     */
    private boolean isExclusion(String requestURI) {
        if (excludesPattens == null) {
            return false;
        } else {
            for(String pattern:excludesPattens) {
                if(pathMatcher.match(pattern, requestURI))
                    return true;
            }
            return false;
        }
    }
}
